﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LS.Common
{
    public class ValidateCodeHelper
    {
        private Brush[] arrayBrushes = new Brush[5] { Brushes.Blue, Brushes.Red, Brushes.Black, Brushes.Green, Brushes.Yellow };
        private Color[] arrayColors = new Color[5] { Color.Blue, Color.Red, Color.Black, Color.Green, Color.Yellow };
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public string RandomCode(int length)
        {
            string s = "0123456789zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP";
            StringBuilder sb = new StringBuilder();
            Random rand = new Random();
            int index;
            for (int i = 0; i < length; i++)
            {
                index = rand.Next(0, s.Length);
                sb.Append(s[index]);
            }
            return sb.ToString();
        }
        public byte[] CreateGraphic(string code, int size = 1)
        {
            //定义壹个画板
            MemoryStream ms = new MemoryStream();
            using (Bitmap map = new Bitmap(68 * size, 34 * size))
            {
                //画笔,在指定画板画板上画图
                //g.Dispose();
                using (Graphics g = Graphics.FromImage(map))
                {
                    g.Clear(Color.White);
                    g.DrawString(code, new Font("黑体", 18.0F * size, FontStyle.Bold), arrayBrushes[new Random().Next(0, 4)], new Point(new Random().Next(0, 30), new Random().Next(0, 20)));
                    //绘制干扰线
                    PaintInterLine(g, 15, map.Width, map.Height);
                    //画像素点  
                    for (int i = 0; i < 100; i++)
                    {
                        Random r = new Random(i);
                        Point p1 = new Point(r.Next(0, map.Width), r.Next(map.Height));
                        Point p2 = new Point(r.Next(0, map.Width), r.Next(0, map.Height));
                        map.SetPixel(p1.X, p1.Y, arrayColors[new Random().Next(0, 4)]);
                    }
                }
                map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            return ms.GetBuffer();
        }
        private void PaintInterLine(Graphics g, int num, int width, int height)
        {
            Random r = new Random();
            int startX, startY, endX, endY;
            for (int i = 0; i < num; i++)
            {
                startX = r.Next(0, width);
                startY = r.Next(0, height);
                endX = r.Next(0, width);
                endY = r.Next(0, height);
                g.DrawLine(new Pen(arrayBrushes[new Random(i).Next(0, 4)], 1), startX, startY, endX, endY);
            }
        }
    }
}
